package com.zero.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zero.yygh.common.exception.CommonException;
import com.zero.yygh.common.helper.HttpRequestHelper;
import com.zero.yygh.common.result.ResultCodeEnum;
import com.zero.yygh.enums.OrderStatusEnum;
import com.zero.yygh.enums.PaymentStatusEnum;
import com.zero.yygh.hosp.client.HospitalFeignClient;
import com.zero.yygh.model.order.OrderInfo;
import com.zero.yygh.model.order.PaymentInfo;
import com.zero.yygh.order.mapper.PaymentInfoMapper;
import com.zero.yygh.order.service.OrderService;
import com.zero.yygh.order.service.PaymentService;
import com.zero.yygh.vo.order.SignInfoVo;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zero
 * @desc
 * @create 2021/5/11
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentService {
    
    @Resource
    private OrderService orderService;
    @Resource
    private HospitalFeignClient hospitalFeignClient;

    /**
     * 保存支付信息
     * @param orderInfo   订单信息
     * @param paymentType 支付类型（1：微信 2：支付宝）
     * @author zero
     * @date 2021/5/11 10:27
     */
    @Override
    public void savePaymentInfo (OrderInfo orderInfo, Integer paymentType) {
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderInfo.getId());
        queryWrapper.eq("payment_type", paymentType);
        Integer count = baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            // 已支付
            return;
        }
        // 否则为未支付
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
        paymentInfo.setOrderId(orderInfo.getId());
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setTotalAmount(orderInfo.getAmount());
        String subject = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + "|" + orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle();
        paymentInfo.setSubject(subject);
        paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus());
        paymentInfo.setCreateTime(new Date());
        baseMapper.insert(paymentInfo);
    }

    /**
     * 支付成功
     * @param outTradeNo 订单号
     * @param status     状态
     * @param resultMap  处理结果
     * @author zero
     * @date 2021/5/11 14:06
     */
    @Override
    public void paySuccess (String outTradeNo, Integer status, Map<String, String> resultMap) {
        PaymentInfo paymentInfo = this.getPaymentInfo(outTradeNo, status);
        if (null == paymentInfo) {
            throw new CommonException(ResultCodeEnum.PARAM_ERROR);
        }
        if (!paymentInfo.getPaymentStatus().equals(PaymentStatusEnum.UNPAID.getStatus())) {
            return;
        }
        //修改支付状态
        PaymentInfo paymentInfoUpd = new PaymentInfo();
        paymentInfoUpd.setPaymentStatus(PaymentStatusEnum.PAID.getStatus());
        paymentInfoUpd.setTradeNo(resultMap.get("transaction_id"));
        paymentInfoUpd.setCallbackTime(new Date());
        paymentInfoUpd.setCallbackContent(resultMap.toString());
        this.updatePaymentInfo(outTradeNo, paymentInfoUpd);
        //修改订单状态
        OrderInfo orderInfo = orderService.getById(paymentInfo.getOrderId());
        orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus());
        orderService.updateById(orderInfo);
        // 调用医院接口，通知更新支付状态
        SignInfoVo signInfoVo
                = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode());
        if(null == signInfoVo) {
            throw new CommonException(ResultCodeEnum.PARAM_ERROR);
        }
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode",orderInfo.getHoscode());
        reqMap.put("hosRecordId",orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
        reqMap.put("sign", sign);
        JSONObject result = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl()+"/order/updatePayStatus");
        if (result.getInteger("code").equals(ResultCodeEnum.SUCCESS.getCode()) ) {
            throw new CommonException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
    }

    /**
     * 获取支付记录
     * @param orderId     订单ID
     * @param paymentType 支付类型
     * @return com.zero.yygh.model.order.PaymentInfo
     * @author zero
     * @date 2021/5/12 10:14
     */
    @Override
    public PaymentInfo getPaymentInfo (Long orderId, Integer paymentType) {
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        queryWrapper.eq("payment_type", paymentType);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 更新支付信息
     * @author zero
     * @date 2021/5/11 14:32
     * @param outTradeNo 订单号
     * @param paymentInfoUpd 支付信息
     */
    private void updatePaymentInfo (String outTradeNo, PaymentInfo paymentInfoUpd) {
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("out_trade_no", outTradeNo);
        baseMapper.update(paymentInfoUpd, queryWrapper);
    }

    /**
     * 获取支付信息
     * @author zero
     * @date 2021/5/11 14:07
     * @param outTradeNo 订单号
     * @param paymentType 支付类型
     * @return com.zero.yygh.model.order.PaymentInfo
     */
    private PaymentInfo getPaymentInfo(String outTradeNo, Integer paymentType) {
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("out_trade_no", outTradeNo);
        queryWrapper.eq("payment_type", paymentType);
        return baseMapper.selectOne(queryWrapper);
    }

}
